package gae.colopl.http.request;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;
import java.util.StringTokenizer;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import gae.colopl.http.ColoplLoginException;
import gae.colopl.http.ColoplRequestException;
import gae.colopl.http.user.Session;
import gae.colopl.http.user.SessionImpl;
import gae.util.http.client.Cookie;
import gae.util.http.client.Header;
import gae.util.http.client.HttpRequest;
import gae.util.http.client.HttpResponse;
import gae.util.http.client.Parameter;

abstract public class AbstractColoplRequest<E> extends ColoplRequestUtil {
    
    private ColoplPCLoginManager loginManager = ColoplPCLoginManager.getInstance();
    
    abstract public HttpRequest createRequest(Session user, Map param) throws ColoplRequestException;
    
    abstract public E parseResponse(HttpResponse res) throws ColoplRequestException;
    
    public E execute(Session session, Map param) throws ColoplRequestException {
        E result = null;
        try {
            if (!session.isLoggedIn()) {
                loginManager.login(session);
            }
            HttpRequest req = createRequest(session, param);
            HttpResponse res = req.execute();
            
            if (res.getStatus() == HttpURLConnection.HTTP_MOVED_TEMP) {
                loginManager.login(session);
                HttpRequest req2 = createRequest(session, param);
                res = req2.execute();
            }
            updateCookie(session, res);
            
            result = parseResponse(res);
        } catch (IOException e) {
            throw new ColoplRequestException(e);
        } catch (ColoplLoginException e) {
            throw new ColoplRequestException(e);
        }
        return result;
    }
    
}
